<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.

 * Sections of this file specific to working with Constant Contact API's are
 * Copyright 2008, Constant Contact and 
 * licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once('includes/functions/module_functions.php');
class constant_contact {

	function constant_contact() 
	{
		$this->module_key = 'MODULE_NEWSLETTER_CONSTANT_CONTACT';
		$this->code = 'constant_contact';
		$this->enabled = ((MODULE_NEWSLETTER_CONSTANT_CONTACT_STATUS == 'true') ? true : false);
		$this->sort_order = MODULE_NEWSLETTER_CONSTANT_CONTACT_SORT_ORDER;
		$this->username = MODULE_NEWSLETTER_CONSTANT_CONTACT_USERNAME;
		$this->password = MODULE_NEWSLETTER_CONSTANT_CONTACT_PASSWORD;
		$this->apikey = MODULE_NEWSLETTER_CONSTANT_CONTACT_APIKEY;
		$this->listname = MODULE_NEWSLETTER_CONSTANT_CONTACT_LISTNAME;
	}

	function process(&$params)
	{
		$this->emailAddress = &$params['emailAddress'];
		$this->firstname = &$params['firstname'];
		$this->lastname = &$params['lastname'];
		$this->company = &$params['company'];

		$this->listId = $this->findContactList();
      		if ($this->listId == -1 || empty($this->listId) || $this->listId == "")
		{
			$errmsg = 'could not find valid list with the name '. $this->listname;
			$this->errorMail($errmsg);
			return;
		}

		$entry = $this->makeEntry();
		$errmsg = $this->addContact($entry);

		if (!$errmsg == "")
		{
			$this->errorMail($errmsg);
		}
        }

	function errorMail(&$errmsg)
	{
		$email_text = $this->listname . " " . $this->emailAddress . " " . $this->firstname . " " . $this->lastname . " " . $this->company . " " . $errmsg;
		send_email(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, 'failed newsletter signup', $email_text, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	}

	function findContactList()
	{
		$request =  "https://api.constantcontact.com/ws/customers/".$this->username."/lists";
		$session = curl_init();
		// Set up Digest authentication - username and password.
		$userNamePassword = $this->apikey."%".$this->username.":".$this->password;
		curl_setopt($session, CURLOPT_URL, $request);
		curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt($session, CURLOPT_USERPWD, $userNamePassword);
		curl_setopt($session, CURLOPT_FOLLOWLOCATION  ,1); 
		curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml")); 
		curl_setopt($session, CURLOPT_HEADER, 0);   // Do not return headers
		curl_setopt($session, CURLOPT_RETURNTRANSFER, 1); 
       		curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, CURLOPT_HTTPPROXYTUNNEL_SETTING);
		if (CURLOPT_HTTPPROXYTUNNEL_SETTING == TRUE)
		{
			if (CURLOPT_PROXYTYPE_SETTING == 'CURLPROXY_SOCKS5') {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
			}
			else {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
			}
        		curl_setopt($session, CURLOPT_PROXY, CURLOPT_PROXY_SETTING);
		}
		curl_setopt($session, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($session, CURLOPT_VERBOSE, 0);
		curl_setopt ($session, CURLOPT_TIMEOUT, 120);
		$response = curl_exec($session);
		curl_close($session);

		if ($response == null) {
			$response = '';
		}
		else {
			$ind = strpos($response, '<');
			if ($ind === false) {
				$response = '';
			}
			else {
				$response = substr($response, $ind);
			}
		}

		//error handling
		if ($response == '') {
			$list_id = -1;        
		} 
		else {
			$data = simplexml_load_string($response);
			foreach($data->entry as $data_entry)
			{
				$entry_name = urlencode($data_entry->content->ContactList->Name);
				if ($entry_name == $this->listname) {
					$list_id=$data_entry->content->ContactList['id'];
				}
			}
		}

		return $list_id;
	}


	public function MakeEntry()
	{
		$xml_sttring = "<entry xmlns='http://www.w3.org/2005/Atom'></entry>";
		$xml_object = simplexml_load_string($xml_sttring);

		$title_node = $xml_object->addChild("title", htmlspecialchars("Hmmm this is ignored right now"));
		$updated_node = $xml_object->addChild("updated", htmlspecialchars(date("Y-m-d").'T'.date("H:i:s").'+01:00'));
		$author_node = $xml_object->addChild("author");
		$author_name = $author_node->addChild("name", htmlspecialchars("CTCT Samples"));
		$id_node = $xml_object->addChild("id", "urn:uuid:E8553C09F4xcvxCCC53F481214230867087");

		$summary_node = $xml_object->addChild("summary", htmlspecialchars("Customer document"));
		$summary_node->addAttribute("type", "text");
		$content_node = $xml_object->addChild("content");
		$content_node->addAttribute("type", "application/vnd.ctct+xml");

		$contact_node = $content_node->addChild("Contact", htmlspecialchars("Customer document"));
		$contact_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/");
		$email_node = $contact_node->addChild("EmailAddress", urldecode(htmlspecialchars($this->emailAddress)));
		$fname_node = $contact_node->addChild("FirstName", urldecode(htmlspecialchars($this->firstname)));
		$lname_node = $contact_node->addChild("LastName", urldecode(htmlspecialchars($this->lastname)));
		$lname_node = $contact_node->addChild("MiddleName", urldecode(htmlspecialchars('')));
		$lname_node = $contact_node->addChild("CompanyName", urldecode(htmlspecialchars($this->company)));
		$lname_node = $contact_node->addChild("JobTitle", urldecode(htmlspecialchars('')));
		$optin_node = $contact_node->addChild("OptInSource", htmlspecialchars("ACTION_BY_CONTACT"));

		$contactlists_node = $contact_node->addChild("ContactLists");
		$contactlist_node = $contactlists_node->addChild("ContactList");
		$contactlist_node->addAttribute("id", $this->listId);

		$entry = $xml_object->asXML();

		return $entry;
    }

	public function addContact($entry)
	{
		$errMsg = '';
		$request =  "https://api.constantcontact.com/ws/customers/".$this->username."/contacts";
		$session = curl_init();
		// Set up Digest authentication - username and password.
		$userNamePassword = $this->apikey."%".$this->username.":".$this->password;
		curl_setopt($session, CURLOPT_URL, $request);
		curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		curl_setopt($session, CURLOPT_USERPWD, $userNamePassword);
		curl_setopt($session, CURLOPT_FOLLOWLOCATION  ,1);
		curl_setopt($session, CURLOPT_POST, 1);
		curl_setopt($session, CURLOPT_POSTFIELDS , $entry);
		curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
		curl_setopt($session, CURLOPT_HEADER, 0);   // Do not return headers
		curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
       		curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, CURLOPT_HTTPPROXYTUNNEL_SETTING);
		if (CURLOPT_HTTPPROXYTUNNEL_SETTING == TRUE)
		{
			if (CURLOPT_PROXYTYPE_SETTING == 'CURLPROXY_SOCKS5') {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
			}
			else {
        			curl_setopt($session, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
			}
        		curl_setopt($session, CURLOPT_PROXY, CURLOPT_PROXY_SETTING);
		}
		curl_setopt($session, CURLOPT_SSL_VERIFYPEER, FALSE);
//$handle = fopen("/home/brozelle/tmp.txt", "w");
//		curl_setopt($session, CURLOPT_STDERR, $handle);
		curl_setopt($session, CURLOPT_VERBOSE, 0);
		curl_setopt ($session, CURLOPT_TIMEOUT, 120);
		$response = curl_exec($session);
		curl_close($session);   
//fclose($handle);

		if ($response == null) {
			$response = '';
		}
		else {
			$ind = strpos($response, '<');
			if ($ind === false) {
				$response = '';
			}
			else {
				$response = substr($response, $ind);
			}
		}

		//error handling
		if ($response == '')
		{
			$errMsg = 'could not add contact, no response from Constant Contact';   
		} 
		else
		{
			$ind = strpos($response, '<');
			$response = substr($response, $ind);
			$data = simplexml_load_string($response);
			$name = $data->getName();
			if ($name == 'error')
			{
				$text = '';
				foreach ($data->children() as $child)
				{
					$text .= $child." ";
				}
				$errMsg .= $text;
			}
		}
		return $errMsg;
	}

	function check() {
		if (!isset($this->_check)) {
			$this->_check = check_module($this->module_key);
		}
		return $this->_check;
	}

	function install() {
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Display Coupon', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_STATUS', 'true', 'Do you want to display the coupon discount?', '6', '1','true, false', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_SORT_ORDER', '1', 'Sort order of display.', '6', '2', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Username', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_USERNAME', '', 'Constant Contact Username', '6', '2', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Password', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_PASSWORD', '', 'Constant Contact Password', '6', '2', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('API Key', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_APIKEY', '', 'API Key', '6', '2', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Listname', 'MODULE_NEWSLETTER_CONSTANT_CONTACT_LISTNAME', 'General+Interest', 'ListName', '6', '2', now())");
	}

	function remove() {
		remove_module($this->module_key);
	}
}
?>
